package com.leyou.goods.service;

import com.leyou.goods.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;
@Service
public class GoodsHtmlService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);

    /**
     * 创建html页面
     *
     * @param spuId
     * @throws Exception
     */
    public void createHtml(Long spuId){
        PrintWriter printWriter = null;
       try {
           Map<String, Object> map = this.goodsService.querySpuById(spuId);

           //创建thymeleaf上下文对象
           Context context = new Context();
           //把数据放入上下文
           context.setVariables(map);

           //创建输出流
           File file = new File("F:\\develop\\nginx-1.14.0\\html\\item\\" + spuId + ".html");
           printWriter = new PrintWriter(file);

           //执行页面静态方法
           templateEngine.process("item",context,printWriter);
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           if(printWriter!=null){
               printWriter.close();
           }
       }
    }
    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId){
        ThreadUtils.execute(() -> createHtml(spuId));
    }

    public void deleteHtml(Long id){
        File file = new File("F:\\develop\\nginx-1.14.0\\html\\item\\" + id + ".html");
        file.deleteOnExit();
    }


}
